import { computed, ref } from "vue";
import { cloneDeep } from "lodash-es";
export function useHistoryUtil<T>(cb?: (data: T) => void) {
  const data = ref<T>();
  let historyList: T[] = [];
  const index = ref(0);
  const updateData = () => {
    data.value = historyList[index.value];
    cb?.(data.value);
  };
  const init = (initialData: T) => {
    historyList = [cloneDeep(initialData)];
    index.value = 0;
    data.value = historyList[index.value];
    cb?.(data.value);
  };

  const commit = (data: T) => {
    const v = cloneDeep(data);
    if (index.value !== historyList.length - 1) {
      // 如果不是最后一个，去除后面的数据
      historyList.splice(
        index.value + 1,
        historyList.length - 1 - index.value,
        v
      );
    } else {
      historyList.push(v);
    }
    index.value = historyList.length - 1;
    updateData();
  };

  const canRedo = computed(() => {
    return index.value < historyList.length - 1;
  });

  const canUndo = computed(() => {
    return index.value > 0;
  });

  const redo = () => {
    if (!canRedo.value) return;
    index.value++;
    updateData();
  };

  const undo = () => {
    if (!canUndo.value) return;
    index.value--;
    updateData();
  };
  const getCloneData = () => {
    return cloneDeep(historyList[index.value]);
  };
  const getHistoryList = () => {
    return historyList;
  };
  return {
    data,
    init,
    commit,
    redo,
    undo,
    canRedo,
    canUndo,
    index,
    getCloneData,
    getHistoryList,
  };
}


export default useHistoryUtil;